const ExcelJS = require("exceljs");
module.exports = function (e, t, n, i, l) {
  let a = {};
  async function o(e, t) {
    l.loginRouter({
      headers: {
        token: e.query.token,
        unitId: e.query.unitId
      }
    }, t, async () => {
      const i = new ExcelJS.Workbook;
      i.creator = "node sys", i.lastModifiedBy = "node sys", i.created = new Date, i.modified = new Date, i.lastPrinted = new Date;
      const l = i.addWorksheet("Sheet 1");
      l.pageSetup.verticalCentered = !0;
      let a = [],
        o = {},
        s = {},
        r = 0;
      for (let t in e.columns) {
        let c = e.columns[t];
        if (/createTimeString|updateTimeString|updateTime|state/.test(t) || !e.columns[t].label) continue;
        if (!/input|onlyselect|textarea|select|switch|radio|datetime|image/.test(c.type || "input")) continue;
        c.index = r, "datetime" == c.type ? o[t] = (e => n.date(e).Format("yyyy-MM-dd hh:mm:ss")) : "select" == c.type || "radio" == c.type ? o[t] = (e => {
          let t = c.attr.actions || [];
          for (let n = 0; n < t.length; n++)
            if (t[n].value == e) return t[n].name;
          return ""
        }) : "switch" == c.type ? o[t] = (e => 1 == e ? "是" : "否") : "onlyselect" == c.type ? o[t] = ((e, t, n, i) => i[t.replace("Id", "Name")] || e) : "image" == c.type && c.canExcel && (s[t] = ((t, a, o, s) => new Promise(r => {
          if (t) {
            let c = t.split(",")[0].trim();
            c = c.indexOf("/file") < 5 ? Config.hosting + c : c, n.node.pipe(require("request")(c), (t, n) => {
              s.height = 100, s._cells[e.columns[a].index].value = "", l.addImage(i.addImage({
                buffer: n,
                extension: c.indexOf(".") > 0 ? c.split()[1] : "png"
              }), {
                tl: {
                  col: e.columns[a].index,
                  row: o
                },
                ext: {
                  width: 130,
                  height: 130
                }
              }), r()
            })
          } else r()
        })));
        let d = {
          alignment: {
            vertical: "middle",
            horizontal: "center"
          },
          header: e.columns[t].label || t,
          key: t,
          width: e.columns[t].width
        };
        "image" == c.type && (d.width = 20), a.push(d), r++
      }
      l.columns = a;
      for (let t = 0; t < e.rows.length; t++) {
        let n = e.rows[t];
        for (let e in o) {
          let i = o[e](n[e], e, t + 1, n);
          n[e] = i
        }
        let i = l.addRow(n);
        for (let e in s) await s[e](n[e], e, t + 1, i)
      }
      l.views = [{
        state: "frozen",
        xSplit: 0,
        ySplit: 1,
        topLeftCell: "special",
        activeCell: "A1"
      }];
      let c = await i.xlsx.writeBuffer(e.filename);
      t.set({
        "Content-Type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "Content-Disposition": `attachment;filename="${encodeURIComponent(e.filename)}.xlsx"`,
        "Content-Length": c.length
      }), t.end(c, "binary")
    })
  }
  return e.get("/modelToExcel/:name", async function (e, i, l) {
    let o = e.params.name,
      s = t[o].schemas,
      r = {};
    a[o] && (a[o].schemas && (s = a[o].schemas), a[o].args && (r = a[o].args)), e.columns = s;
    let c = e.query;
    c.pageNum = null, c.pageSize = null, c.unitId = "all" == c.unitId ? void 0 : c.unitId, c.createTime = c.createTime || {
      $gte: (new Date).getTime() - 2592e6
    }, e.rows = await t[o].listSync(c, r);
    let d = a[o] && a[o].nickName || t[o].nickName || "";
    e.filename = d + "_" + n.guid(), l()
  }, o), {
    toExcelRouter: o,
    ExcelJS: ExcelJS
  }
};